<!--
 * @Description: 商品采集(2021/09/09优化)
 * @Author: liyujie
 * @Date: 2021/7/7
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/7/7
-->

<template>
    <PageLayout title="商品采集">
        <!-- 筛选-->
        <template slot="filter">
            <div class="filter-item">
                <p class="filter-item__title">
                    商品平台
                </p>
                <el-select
                    v-model="filterData.shop_social_type"
                    size="small"
                    filterable
                    style="width: 152px"
                    @change="handleChangeType"
                >
                    <el-option
                        label="淘宝"
                        :value="1"
                    />
                    <el-option
                        label="京东"
                        :value="2"
                    />
                    <el-option
                        label="拼多多"
                        :value="3"
                    />
                </el-select>
            </div>
            <div class="filter-item">
                <p class="filter-item__title">
                    商品分类
                </p>
                <el-cascader
                    placeholder="请选择"
                    :options="typeList"
                    filterable
                    clearable
                    size="small"
                    change-on-select
                    expand-trigger="hover"
                    v-model="filterData.selectedType"
                    @change="getTableData(1)"
                    :props="{
                        label: 'title',
                        value: 'cid',
                        children: 'children'
                    }"
                />
            </div>
            <div class="filter-item">
                <p class="filter-item__title">
                    关键词
                </p>
                <el-input
                    v-model="filterData.keyword"
                    placeholder="可搜索关键词/商品ID/商品链接"
                    clearable
                    size="small"
                    @keyup.native.enter="getTableData(1)"
                />
            </div>
            <div class="filter-item">
                <p class="filter-item__title">
                    价格
                </p>
                <div>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.minPrice"
                        :min="0"
                        size="small"
                    />
                    <span class="el-divison">-</span>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.maxPrice"
                        :min="0"
                        size="small"
                    />
                </div>
            </div>
            <div class="filter-item">
                <p class="filter-item__title">
                    券额
                </p>
                <div>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.coupon_money"
                        :min="0"
                        size="small"
                    />
                    <span class="el-divison">-</span>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.coupon_moneyEnd"
                        :min="0"
                        size="small"
                    />
                </div>
            </div>
            <div class="filter-item">
                <p class="filter-item__title">
                    佣金比例
                </p>
                <div>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.commission_rate"
                        :min="0"
                        size="small"
                    />
                    <span class="el-divison">-</span>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.commission_rateEnd"
                        :min="0"
                        size="small"
                    />
                </div>
            </div>
            <div class="filter-item">
                <p class="filter-item__title">
                    佣金比例
                </p>
                <div>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.commission_rate"
                        :min="0"
                        size="small"
                    />
                    <span class="el-divison">-</span>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.commission_rateEnd"
                        :min="0"
                        size="small"
                    />
                </div>
            </div>
            <div class="filter-item">
                <p class="filter-item__title">
                    月销量
                </p>
                <div>
                    <el-input
                        class="number-input"
                        clearable
                        type="number"
                        style="width: 130px"
                        v-model="filterData.item_sale"
                        :min="0"
                        size="small"
                    />
                    <span class="el-divison">-</span>
                    <el-input
                        class="number-input"
                        style="width: 130px"
                        clearable
                        type="number"
                        v-model="filterData.item_saleEnd"
                        :min="0"
                        size="small"
                    />
                </div>
            </div>
            <div class="filter-item">
                <el-button
                    type="primary"
                    size="small"
                    class="query-button"
                    @click="getTableData(1)"
                >
                    查询
                </el-button>
            </div>
        </template>
        <el-table
            :data="tableData"
            height="100%"
            style="width: 100%;"
            ref="goodsTable"
            row-key="item_id"
            class="data-table"
            v-loading="tableLoading"
            @select="fnSelect"
            @select-all="fnSelectAllTop"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChanged"
        >
            <el-table-column
                fixed="left"
                type="selection"
                align="center"
                width="60"
            />
            <el-table-column
                fixed="left"
                prop="item_title"
                min-width="200"
                show-overflow-tooltip
                label="商品名称"
            >
                <template slot-scope="scope">
                    <span
                        @click="fnGoShoplist(scope.row.item_url)"
                        class="shop-item-jump"
                    >{{ scope.row.item_title }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="seller_nick"
                :width="200"
                label="店铺名称"
                show-overflow-tooltip
            />
            <el-table-column
                align="center"
                label="商品平台"
                show-overflow-tooltip
            >
                <template slot-scope="scope">
                    {{ scope.row.shop_social_type | socialFilter }}
                </template>
            </el-table-column>
            <el-table-column
                prop="cname"
                min-width="110"
                label="一级类目"
            />
            <el-table-column
                prop="sub_cname"
                min-width="110"
                label="二级类目"
            />
            <el-table-column
                prop="seller_type"
                min-width="110"
                :formatter="typeFormatter"
                label="店铺类别"
            />
            <el-table-column
                prop="item_cover"
                min-width="110"
                label="商品缩略图"
            >
                <template slot-scope="scope">
                    <img
                        :src="scope.row.item_cover"
                        class="img-cover">
                </template>
            </el-table-column>
            <el-table-column
                prop="item_price"
                min-width="110"
                label="价格"
                sortable="custom"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="item_price_origin"
                min-width="110"
                label="原价"
                sortable="custom"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="item_discount"
                min-width="110"
                label="折率"
                sortable="custom"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="item_commission_rate"
                min-width="110"
                label="佣金比例"
                sortable="custom"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="item_sale"
                min-width="110"
                label="30天销量"
                sortable="custom"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="item_commission"
                min-width="110"
                label="佣金金额"
                sortable="custom"
            />
            <el-table-column
                prop="item_commission_type"
                min-width="110"
                :formatter="yongTypeFormatter"
                label="佣金类型"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="coupon_money"
                min-width="110"
                label="优惠券金额"
                sortable="custom"
                :width="130"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="coupon_total_count"
                min-width="110"
                label="券总量"
                sortable="custom"
            />
            <el-table-column
                :formatter="emptyFormatter"
                prop="coupon_receive_count"
                min-width="110"
                label="领券量"
                sortable="custom"
            />
            <el-table-column
                prop="coupon_end_time"
                min-width="140"
                label="优惠券结束时间"
            >
                <template slot-scope="scope">
                    <template v-if="scope.row.coupon_end_time">
                        {{ scope.row.coupon_end_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                    </template>
                    <template v-else>--</template>
                </template>
            </el-table-column>
            <el-table-column
                prop="coupon_start_time"
                min-width="140"
                label="优惠券开始时间"
            >
                <template slot-scope="scope">
                    <template v-if="scope.row.coupon_start_time">
                        {{ scope.row.coupon_start_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                    </template>
                    <template v-else>--</template>
                </template>
            </el-table-column>
            <el-table-column
                prop="date"
                label="操作"
                fixed="right"
                width="200"
            >
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        @click="fnChoose(scope.row.item_id)"
                    >采集
                    </el-button>
                    <el-button
                        type="text"
                        @click="fnDelete(scope.row.item_id)"
                    >排除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <template slot="pagination">
            <div>
                <el-checkbox
                    v-model="checkedAll"
                    :indeterminate="checkIndeterminate"
                    @change="fnChangeChecked"
                >全选
                </el-checkbox>
                <el-button
                    size="medium"
                    style="margin-left: 12px"
                    type="text"
                    :disabled="multipleSelection.length === 0"
                    @click="fnChoseBatch()"
                >批量采集
                </el-button>
                <el-button
                    size="medium"
                    type="text"
                    :disabled="multipleSelection.length === 0"
                    @click="fnChoseDelte()"
                >批量排除
                </el-button>
            </div>
            <el-pagination
                layout="total,sizes, prev, pager, next, jumper"
                background
                :total="page.total_count"
                :page-size="page.page_size"
                :current-page="page.now_page"
                @current-change="getTableData"
                @size-change="handleSizeChange"
            />
        </template>
    </PageLayout>
</template>

<script>
export default {
    data() {
        return {
            authResult: {},
            checkedAll: false,
            checkIndeterminate: false,
            multipleSelection: [],
            typeList: [],
            tableData: [],
            filterData: {
                selectedType: [],//选中分类
                maxPrice: '',
                minPrice: '',
                coupon_money: '',
                coupon_moneyEnd: '',
                commission_rate: '',
                commission_rateEnd: '',
                item_sale: '',
                item_saleEnd: '',
                sort_field: '',
                sort_type: '',
                keyword: '',
                shop_social_type: 1
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 50
            },

            tableLoading: false
        };
    },
    computed: {
        checkAllStatus: {
            get() {
                if (this.multipleSelection.length == 0) {
                    return false;
                } else if (this.multipleSelection.length == this.tableData.length) {
                    return true;
                }
            },
            set() {
                return true;
            }
        },
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.init();
        this.fnGetGoodsType();
    },
    filters: {
        socialFilter(val) {
            switch (val) {
                case 1:
                    return '淘宝';
                case 2:
                    return '京东';
                case 3:
                    return '拼多多';
                default:
                    return '--';
            }
        },
    },
    methods: {
        /**
         * 初始化
         */
        init() {
            this.$store.commit('SET_HEADER', [
                {title: "APP后台"}, {title: "商城"},{title: '商品列表', path: '/student/goods-list'},{title: '商品采集'}
            ]);

            this.getTableData();
        },
        /** 商品二级分类 */
        fnGetGoodsType() {
            this.$post('/student/shop_goods_collect%5Ctype_list', {
                shop_social_type: this.filterData.shop_social_type
            }, resp => {
                if (resp.code == 1) {
                    this.typeList = resp.data.list;
                }
            });
        },

        /**
         * 获取表格数据
         */
        getTableData(page) {
            this.tableLoading = true;
            this.checkedAll = false;

            if (this.filterData.minPrice < 0) {
                this.filterData.minPrice = 0;
            }
            if (this.filterData.maxPrice < 0) {
                this.filterData.maxPrice = 0;
            }
            if (this.filterData.minPrice && this.filterData.maxPrice && this.filterData.minPrice > this.filterData.maxPrice) {
                let tmp = this.filterData.minPrice;

                this.filterData.minPrice = this.filterData.maxPrice;
                this.filterData.maxPrice = tmp;
            }
            let query = {
                cid: '',
                sub_cid: '',
                price_range: this.filterData.minPrice + '-' + this.filterData.maxPrice,
                coupon_money_range: this.filterData.coupon_money + '-' + this.filterData.coupon_moneyEnd,
                commission_rate_range: this.filterData.commission_rate + '-' + this.filterData.commission_rateEnd,
                item_sale_range: this.filterData.item_sale + '-' + this.filterData.item_saleEnd,
                sort_field: this.filterData.sort_field,
                sort_type: this.filterData.sort_type,
                keyword: this.filterData.keyword,
                page_id: page || this.page.now_page,
                shop_social_type: this.filterData.shop_social_type,
                page_size: this.page.page_size
            };

            if (this.filterData.selectedType && this.filterData.selectedType.length >= 1) {
                query.cid = this.filterData.selectedType[0];
            }

            if (this.filterData.selectedType && this.filterData.selectedType.length == 2) {
                query.sub_cid = this.filterData.selectedType[1];
            }

            // this.$router.replace({
            //     name: this.$route.name,
            //     query:query
            // });
            this.$post('/student/shop_goods_collect%5Csearch', query, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                    if (resp.data.page.total_page > 0 && resp.data.page.total_page < resp.data.page.now_page) {
                        this.getTableData(resp.data.page.total_page);
                    }
                }
                this.tableLoading = false;
            });
        },
        fnSelect(selection) {
            if (selection.length == this.tableData.length) {
                this.checkedAll = true;
            } else {
                this.checkedAll = false;
            }

            // 改变全选checkbox 的显示状态
            if (selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            } else {
                this.checkIndeterminate = false;
            }
        },
        fnSelectAllTop(selection) {
            if (selection.length > 0) {
                this.checkedAll = true;
            } else {
                this.checkedAll = false;
            }

            // 改变全选checkbox 的显示状态
            if (selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            } else {
                this.checkIndeterminate = false;
            }
        },
        fnChangeChecked() {
            if (this.checkedAll) {
                this.toggleSelection(1);
            } else {
                this.toggleSelection();
            }
        },
        toggleSelection(rows) {
            if (rows) {
                this.$refs.goodsTable.toggleAllSelection();
            } else {
                this.$refs.goodsTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        /**
         * 清空筛选数据
         */
        handleResetFilter() {
            this.filterData = {
                title: '',
                type: '0',
                money_type: '0',
                status: '0',
                start_time: '',
                end_time: '',
            };

            this.getTableData(1);
        },

        fnClearFidlds(name) {
            this.$refs[name].resetFields();
        },

        /**
         * 列表渲染辅助函数：列表项为空处理
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        },
        typeFormatter(row, column, val) {
            if (!val) {
                return '--';
            } else if (val == 0) {
                return '淘宝';
            } else if (val == 1) {
                return '天猫';
            } else {
                return '--';
            }
        },
        yongTypeFormatter(row, column, val) {
            if (!val) {
                return '--';
            } else if (val == 0) {
                return '通用';
            } else if (val == 1) {
                return '定向';
            } else if (val == 2) {
                return '高佣';
            } else if (val == 3) {
                return '营销计划';
            } else {
                return '--';
            }
        },
        fnChoose(no) {
            this.$post('/student/shop_goods_collect%5Ccollect', {
                item_id_json: JSON.stringify([no]),
                shop_social_type: this.filterData.shop_social_type
            }, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        center: true,
                        message: '采集成功'
                    });
                    this.getTableData();
                } else {
                    this.$message({
                        type: 'warning',
                        center: true,
                        message: resp.msg
                    });
                }
            });
        },
        fnDelete(no) {
            this.$confirm('确认要排除此商品？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/shop_goods_collect%5Cignore', {
                    item_id_json: JSON.stringify([no]),
                    shop_social_type: this.filterData.shop_social_type
                }, resp => {
                    if (resp.code == 1) {
                        this.$message({
                            type: 'success',
                            center: true,
                            message: '排除成功'
                        });
                        this.getTableData();
                    } else {
                        this.$message({
                            type: 'warning',
                            center: true,
                            message: resp.msg
                        });
                    }
                });
            });
        },
        fnChoseBatch() {
            let selected = this.multipleSelection.map(val => {
                return val.item_id;
            });

            this.$post('/student/shop_goods_collect%5Ccollect', {
                item_id_json: JSON.stringify(selected),
                shop_social_type: this.filterData.shop_social_type
            }, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        center: true,
                        message: '采集成功'
                    });
                    this.getTableData();
                } else {
                    this.$message({
                        type: 'warning',
                        center: true,
                        message: resp.msg
                    });
                }
            });
        },
        /**
         * 批量排除
         */
        fnChoseDelte() {
            let selected = this.multipleSelection.map(val => {
                return val.item_id;
            });

            this.$post('/student/shop_goods_collect%5Cignore', {
                item_id_json: JSON.stringify(selected),
                shop_social_type: this.filterData.shop_social_type
            }, resp => {
                if (resp.code == 1) {
                    this.getTableData(1);
                    this.$message({
                        type: 'success',
                        center: true,
                        message: '排除成功'
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        center: true,
                        message: resp.msg
                    });
                }
            });
        },
        // fnChangeSort() {
        //     if (!this.filterData.sort_field) {
        //         this.filterData.sort_type = '';
        //     } else if (this.filterData.sort_field == 'price') {
        //         this.filterData.sort_type = 'asc';
        //     } else {
        //         this.filterData.sort_type = 'desc';
        //     }
        //     this.getTableData(1);
        // },
        handleSortChanged(data) {

            let sortTypeMap = {
                ascending: 'asc',
                descending: 'desc'
            };

            let sortFieldMap = {
                "item_price": 'price',
                "item_price_origin": 'origin_price',
                "item_discount": 'discount',
                "item_sale": "sale",
                "item_commission": "commission",
                "coupon_money": "coupon_money",
                "coupon_total_count": "coupon_total",
                "coupon_receive_count": "coupon_receive",
                "": ""

            };

            if (data.order) {
                this.filterData.sort_field = sortFieldMap[data.prop];
                this.filterData.sort_type = sortTypeMap[data.order];
            } else {
                this.filterData.sort_field = '';
                this.filterData.sort_type = '';
            }

            this.getTableData();
        },

        fnGoShoplist(link) {
            if (link !== '') {
                window.open(link);
            } else {
                this.$message({
                    type: 'warning',
                    message: '链接不可以为空'
                });
            }
        },

        /**
         * 切换商品平台
         */
        handleChangeType() {
            this.filterData.selectedType = [];
            this.fnGetGoodsType();
            this.getTableData(1);
        },

        /**
         * 每页条数更改
         * @param page_size
         */
        handleSizeChange(page_size) {
            this.page.page_size = page_size;
            this.getTableData();
        },
    }
};
</script>

<style lang="less" scoped>
/deep/ .filter-wrapper {
    margin-top: 12px!important;
    .filter-item {
        margin-bottom: 12px!important;
    }
}
.el-divison {
    margin: 0 8px;
}

.img-cover {
    width: 50px;
    height: 50px;
}

.shop-item-jump {
    cursor: pointer;
    color: #409EFF;
}
/deep/ .el-input {
    width: inherit;
}

</style>
<style lang="less">
.number-input {
    width: 130px;

    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
        -webkit-appearance: none;
    }
}
</style>
